<script lang="ts" setup>
import { trimBlank } from '@vc/utils';
import { genFileId } from 'element-plus';
import message from 'vc/src/common/message';
import { reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { useUserStore } from '@/store/modules/user';
import { changeAvatar, submitUserAuthentication, uploadAuth, userEdit } from '../../apis/profile';
import { noEmpty } from '../../config';

interface Props {
  showDialog: boolean;
  isEdit?: boolean;
}

const {
  showDialog,
  isEdit
} = defineProps<Props>();

const emit = defineEmits(['update:showDialog']);

const ruleFormRef = ref<FormInstance>();

const userStore = useUserStore();

const ruleForm = reactive({
  realName: userStore.getUserInfo.realName,
  businessCardFileId: '',
  companyAddress: userStore.getUserInfo.companyAddress,
  job: userStore.getUserInfo.job,
  industry: userStore.getUserInfo.industry,
  company: userStore.getUserInfo.company
});

let isChange = $ref(false);

const upload = ref();
let uploadFile = $ref('');

watch([() => ruleForm, () => uploadFile], () => {
  isChange = true;
}, {
  deep: true
});

const handleExceed = (files) => {
  upload.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

const { data, run } = useRequest(uploadAuth, {
  manual: true
});

const { run: reqChange, loading } = useRequest(submitUserAuthentication, {
  manual: true
});

const handleChange = (_uploadFile) => {
  const isJpgOrPng = _uploadFile.raw.type === 'image/jpg' || _uploadFile.raw.type === 'image/jpeg' || _uploadFile.raw.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('支持的文件格式为：jpg/jpeg/png');
    upload.value!.clearFiles();
    uploadFile = '';
    return false;
  } else if (_uploadFile.raw.size / 1024 / 1024 > 1) {
    message.error('图片大小不能超过 1 MB!');
    upload.value!.clearFiles();
    uploadFile = '';
    return false;
  } else {
    uploadFile = _uploadFile.raw;
  }
};

const handleSubmit = async() => {
  await ruleFormRef.value!.validate(async(valid) => {
    if (valid) {
      if (isChange) {
        if (!userStore.getUserInfo.businessCardUrl) {
          if (uploadFile) {
            run(uploadFile).then(() => {
              ruleForm.businessCardFileId = data.value?.[0]?.uuid;
              if (ruleForm.businessCardFileId) {
                handleSubmitFn();
              }
            });
          } else {
            message.error('请上传名片');
          }
        } else {
          if (uploadFile) {
            run(uploadFile).then(() => {
              ruleForm.businessCardFileId = data.value?.[0]?.uuid;
              if (ruleForm.businessCardFileId) {
                handleSubmitFn();
              }
            });
          } else {
            handleSubmitFn();
          }
        }
      }
    }
  });
};

const handleSubmitFn = () => {
  reqChange(ruleForm).then((res) => {
    if (res.code === 200) {
      message.success('修改成功');
      isChange = false;
      userStore.getUserInfoAction();
    } else {
      message.error(res.msg);
    }
  });
};

function handleReset () {
  uploadFile = '';
  ruleFormRef.value!.resetFields();
  upload.value!.clearFiles();
  setTimeout(() => {
    isChange = false;
  });
}
</script>

<template>
  <div class="content">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      label-position="left"
      label-width="104px"
      @keypress.enter="handleSubmit"
    >
      <el-form-item class="businessCard" label="上传名片" prop="businessCardFileId">
        <img v-if="!uploadFile && userStore.getUserInfo.businessCardUrl"
          class="mr-8px border border-[#dcdfe6] w-146px h-146px"
          :src="userStore.getUserInfo.businessCardUrl" alt="" />
        <el-upload ref="upload" list-type="picture-card"
          :on-exceed="handleExceed"
          :on-change="handleChange"
          :auto-upload="false"
          :limit="1"
        >
          <vc-icon icon="vi-add" />
          <template #file="{ file }">
            <div class="w-full text-center">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item :rules="[noEmpty('')]" label="真实姓名" prop="realName">
        <el-input maxlength="10" class="input" placeholder="请输入真实姓名"
          v-model="ruleForm.realName" />
      </el-form-item>
      <el-form-item :rules="[noEmpty('')]" label="企业名称" prop="company">
        <el-input maxlength="50" class="input" placeholder="请输入您所在的企业名称"
          v-model="ruleForm.company" />
      </el-form-item>
      <el-form-item :rules="[noEmpty('')]" label="行业名称" prop="industry">
        <el-input maxlength="50" class="input" placeholder="请输入您所在的行业名称"
          v-model="ruleForm.industry" />
      </el-form-item>
      <el-form-item :rules="[noEmpty('')]" label="职务名称" prop="job">
        <el-input maxlength="20" class="input" placeholder="请输入您的职务名称"
          v-model="ruleForm.job" />
      </el-form-item>
      <el-form-item :rules="[noEmpty('')]" label="公司地址" prop="companyAddress">
        <el-input maxlength="100" class="input" placeholder="请输入公司详细地址"
          v-model="ruleForm.companyAddress" />
      </el-form-item>
      <el-form-item class="fr">
        <el-button class="change-color" @click="handleReset">重置</el-button>
        <el-button :disabled="!isChange" :loading="loading" type="primary" color="#02C680" style="color:#FFFFFF;" @click="handleSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.content {
  padding: 24px;
  width: 460px;
  
  :deep(.businessCard) {
    height: 146px;
    .el-upload-list__item {
      transition: none;
      margin: 0 8px 0px 0;
    }
    .el-upload--picture-card:hover,.el-upload:focus{
      color: #02C680;
      border-color: #02C680;
    }
  }
}
:deep(.input){
  .is-focus{
    box-shadow: 0 0 0 1px #02C680 inset;
  }
}
:deep(.content) {
  .el-form-item__label {
    margin-top: 4px;
    &::before {
      content: '';
      display: none;
    }
  }
}
:deep(.change-color){
  &:hover{
    color: #02C680;
    background-color: rgba(231,247,243,0.3);
    border-color: #02C680;
  }
  &:focus{
    color: #02C680;
    background-color: rgba(231,247,243,0.3);
    border-color: #02C680;
  }
}
</style>
